package org.ling.xuan.pannel;

import cn.hutool.core.io.FileUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.table.TableView;
import org.ling.xuan.common.CommonBizUtil;
import org.ling.xuan.dao.FileDao;
import org.ling.xuan.dao.LocalAddDao;
import org.ling.xuan.dao.MarkFileDao;
import org.ling.xuan.dialog.AddFileListDialog;
import org.ling.xuan.dialog.SvnCommitSureDialog;
import org.ling.xuan.entity.AddInfoContext;
import org.ling.xuan.entity.mo.LocalAdd;
import org.ling.xuan.entity.mo.MarkFile;
import org.ling.xuan.entity.mo.SvnCommitCheck;
import org.ling.xuan.table.LocalAddTableModel;
import org.ling.xuan.util.LoggerUtil;
import org.ling.xuan.util.LxIoUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LocalAddListPanel extends JBPanel {
    private TableView<LocalAdd> table;
    private JButton fileButton;
    private JButton deleteButton;
    private JButton showInfoButton;
    private JButton svnSubmitButton;
    private JButton reModifyButton;
    private JButton emailSend;
    private final Project project;
    private JButton reAddButton;
    private final JButton searchButton=new JButton("搜索");
    private final JBTextField msgText = new JBTextField(15);
    private final JBTextField modifyIdText = new JBTextField(15);
    private final JBTextField requireIdText = new JBTextField(15);
    private final JBTextField bankNameText = new JBTextField(15);
    private final JBTextField fileNameText = new JBTextField(15);
    private List<LocalAdd> list;
    private LocalAddTableModel tableModel = new LocalAddTableModel(new ArrayList<>());
    private JBScrollPane scrollPane;
    public LocalAddListPanel(Project project) {
        this.project = project;
        if(list==null) {
            list = LocalAddDao.searchByCondition(modifyIdText.getText(),msgText.getText(),requireIdText.getText(),fileNameText.getText(),bankNameText.getText());
            list = list.stream().filter(l -> !l.isCur()).collect(Collectors.toList());
            initializeUI(list);
        }
    }


    private void initializeUI(List<LocalAdd> localAddList) {
        this.setLayout(new BorderLayout());
        // 创建表格模型
        tableModel = new LocalAddTableModel(localAddList);
        TableView<LocalAdd> table = new TableView<>(tableModel);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    int row = table.rowAtPoint(e.getPoint());
                    int col = table.columnAtPoint(e.getPoint());
                    if (row >= 0 && col >= 0) {
                        Object value = table.getValueAt(row, col);
                        StringSelection selection = new StringSelection(value.toString());
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
                    }
                }
            }
        });
        // 创建滚动面板，并将表格添加到滚动面板中
        scrollPane = new JBScrollPane(table);
        // 隐藏 id 列
        table.getColumnModel().getColumn(0).setWidth(0);
        table.getColumnModel().getColumn(0).setMinWidth(0);
        table.getColumnModel().getColumn(0).setMaxWidth(0);
        // 创建删除按钮
        fileButton = new JButton("查看文件");
        fileButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            String id = (String) table.getValueAt(selectedRow, 0);
            String modifyId = (String) table.getValueAt(selectedRow, 1);
            LoggerUtil.log(project, "-----------showInfo:addId:{},modifyId:{}------------", id, modifyId);
            List<MarkFile> files = MarkFileDao.listByAddId(modifyId);
            AddFileListDialog fileDialog = new AddFileListDialog(project, true, files,false);
            fileDialog.show();
        });
        showInfoButton = new JButton("输出提交");
        showInfoButton.addActionListener(e -> {
            int[] selectedRows = table.getSelectedRows();
            for (int selectedRow : selectedRows) {
                String id = (String) table.getValueAt(selectedRow, 0);
                String modifyId = (String) table.getValueAt(selectedRow, 1);
                LoggerUtil.log(project, "-----------showInfo:addId:{},modifyId:{}------------", id, modifyId);
                AddInfoContext addInfoContext = FileDao.getAddInfoContext(id);
                LoggerUtil.log(project, addInfoContext.getAddMsg());
            }
        });
        svnSubmitButton = new JButton("svn提交");
        svnSubmitButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                String id = (String) table.getValueAt(selectedRow, 0);
                String modifyId = (String) table.getValueAt(selectedRow, 1);
                String commited = (String) table.getValueAt(selectedRow, 3);
                if (!"true".equals(commited)) {
                    LoggerUtil.log(project, "-----------Svn Commit:addId:{},modifyId:{}------------", id, modifyId);
                    AddInfoContext addInfoContext = FileDao.getAddInfoContext(id);
                    List<MarkFile> fileInfos = MarkFileDao.listByAddId(id);
                    List<String> filePaths = fileInfos.stream().filter(markFile ->!markFile.isRelation()).map(MarkFile::getFilePath).filter(FileUtil::exist).collect(Collectors.toList());
                    List<SvnCommitCheck> svnCommitChecks = CommonBizUtil.getSvnCommitCheck(addInfoContext.getSettingMap(), filePaths);
                    SvnCommitSureDialog dialog = new SvnCommitSureDialog(project, true, svnCommitChecks);
                    if (dialog.showAndGet()) {
                        List<SvnCommitCheck> commitChecks = dialog.getSuccessFiles();
                        if (commitChecks.size() > 0) {
                            try {
                                boolean f =CommonBizUtil.addAndCommit(project, commitChecks, addInfoContext.getAddMsg());
                                if(f) {
                                    LocalAddDao.svnCommitSuccess(id);
                                    table.setValueAt("true", selectedRow, 3);
                                    tableModel.setValueAt("true", selectedRow, 3);
                                }
                            } catch (Exception se) {
                                LoggerUtil.log(project, "提交失败：{}", e);
                                throw new RuntimeException("svn提交失败,请查看日志");
                            }
                        } else {
                            Messages.showWarningDialog("没有可提交文件", "提示");
                        }
                    }
                }
            }else{
                Messages.showWarningDialog("已经提交过了","提示");
            }
            refreshTable();
        });
        deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                String id = (String) table.getValueAt(selectedRow, 0);
                String modifyId = (String) table.getValueAt(selectedRow, 1);
                LoggerUtil.log(project, "-----------delete :addId:{},modifyId:{}------------", id, modifyId);
                String root = LxIoUtil.getWorkHome() + "/.lx/add/" + id;
                FileUtil.del(root);
                LocalAddDao.delete(id);
                table.remove(selectedRow);
                tableModel.removeRow(selectedRow);
            }
            refreshTable();
        });
        emailSend = new JButton("邮件发送");
        emailSend.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                String id = (String) table.getValueAt(selectedRow, 0);
                String modifyId = (String) table.getValueAt(selectedRow, 1);
                String send = (String) table.getValueAt(selectedRow, 4);
                if (!"true".equals(send)) {
                    LoggerUtil.log(project, "-----------email send :addId:{},modifyId:{}------------", id, modifyId);
                    try {
                         boolean f =CommonBizUtil.sendAddEmail(project, id);
                         if(f) {
                             table.setValueAt("true", selectedRow, 4);
                             tableModel.setValueAt("true", selectedRow, 4);
                         }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        LoggerUtil.log(project, "发送失败：{}", e1);
                        Messages.showWarningDialog("发送失败,请查看日志", "提示");
                    }
                }else{
                    Messages.showWarningDialog("已经发送过了","提示");
                }
            }
            refreshTable();
        });
        reModifyButton = new JButton("再次修改");
        reModifyButton.addActionListener(e->{
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                String id = (String) table.getValueAt(selectedRow, 0);
                LocalAdd add = LocalAddDao.getById(id);
                LocalAdd cur = LocalAddDao.getCur();
                add.copy2Cur(cur);
                LocalAddDao.updateCurAddSimple(cur);
                List<MarkFile> markFiles = MarkFileDao.listByAddId(id);
                for(MarkFile markFile:markFiles){
                    if(MarkFileDao.canMark(markFile.getFilePath(),null)){
                        MarkFile mk = markFile.toNewMark();
                        MarkFileDao.addMarkFile(mk);
                    }
                }
            }
            refreshTable();
            Messages.showMessageDialog("操作成功","成功",Messages.getInformationIcon());
        });
        reAddButton = new JButton("重新打包");
        reAddButton.addActionListener(e->{
            int[] selectedRows = table.getSelectedRows();
            for (int selectedRow : selectedRows) {
                String id = (String) table.getValueAt(selectedRow, 0);
                String modifyId = (String) table.getValueAt(selectedRow, 1);
                LoggerUtil.log(project, "-----------showInfo:addId:{},modifyId:{}------------", id, modifyId);
                List<String> modifyFiles = MarkFileDao.listFileByAddId(id,false);
                int i =CommonBizUtil.checkFiles(project,modifyFiles,LocalAddDao.getById(id));
                boolean next = true;
                if (i != 1) {
                    next = false;
                    String msg = "";
                    if (i == 0) {
                        msg = "检测不通过,是否继续";
                    } else {
                        msg = "存在告警,是否继续";
                    }
                    int result = Messages.showOkCancelDialog(project, msg, "提示", "继续", "放弃", Messages.getWarningIcon());
                    if (result == 0) {
                        next = true;
                    }
                }
                if (next) {
                    if(CommonBizUtil.add(project,id)) {
                        LocalAddDao.initSendAndCommitStatus(id);
                        table.setValueAt("false", selectedRow, 3);
                        tableModel.setValueAt("false", selectedRow, 3);
                        table.setValueAt("true", selectedRow, 4);
                        tableModel.setValueAt("true", selectedRow, 4);
                        refreshTable();
                    }
                }
            }

        });
        this.add(scrollPane, BorderLayout.CENTER);
        JPanel jPanel = new JBPanel<>();
        jPanel.setLayout(new GridLayout(1, 6));
        jPanel.add(fileButton);
        jPanel.add(showInfoButton);
        jPanel.add(svnSubmitButton);
        jPanel.add(emailSend);
        jPanel.add(deleteButton);
        jPanel.add(reModifyButton);
        jPanel.add(reAddButton);
        this.add(jPanel, BorderLayout.SOUTH);
        JPanel condition = new JBPanel<>();
        jPanel.setLayout(new GridLayout(1, 6));
        JPanel panel1 = new JPanel();
        panel1.add(new JLabel("修改单号:"));
        panel1.add(modifyIdText);

        JPanel panel5 = new JPanel();
        panel5.add(new JLabel("提交信息:"));
        panel5.add(msgText);
        
        JPanel panel2 = new JPanel();
        panel2.add(new JLabel("需求编号:"));
        panel2.add(requireIdText);

        JPanel panel3 = new JPanel();
        panel3.add(new JLabel("银行名称:"));
        panel3.add(bankNameText);

        JPanel panel4 = new JPanel();
        panel4.add(new JLabel("文件名称:"));
        panel4.add(fileNameText);
   
        condition.add(panel1);
        condition.add(panel5);
        condition.add(panel2);
        condition.add(panel3);
        condition.add(panel4);
        condition.add(searchButton);
        searchButton.addActionListener((e)->{
            refreshTable();
        });
        searchButton.setSelected(true);
        this.add(condition, BorderLayout.NORTH);
    }

    private void refreshTable(){
        list = LocalAddDao.searchByCondition(modifyIdText.getText(),msgText.getText(),requireIdText.getText(),fileNameText.getText(),bankNameText.getText());
        list = list.stream().filter(l -> !l.isCur()).collect(Collectors.toList());
        tableModel.refreshData(list);
/*        if(table!=null) {
            table.repaint();
        }*/
    }
}
